import { BaseService } from '../framework/base-service.js'

export default class TestService extends BaseService {
  static metadata = {
    name: 'test',
    version: '1.0.0',
    description: '测试服务，验证核心属性访问',
    dependencies: [],
    singleton: true
  }
  
  async onInit() {
    // 测试核心服务访问
    this.logger.info('TestService', '初始化测试服务')
    this.logger.debug('TestService', `配置端口: ${this.config.get('base.port')}`)
  }
  
  async onStart() {
    this.logger.info('TestService', '启动测试服务')
    
    // 测试数据库访问
    const result = this.db.prepare('SELECT 1 as test').get()
    this.logger.debug('TestService', '数据库测试', { result })
    
    // 测试事件系统
    this.eventBus.on('test.ping', data => {
      this.logger.info('TestService', 'Received ping', data)
      this.eventBus.emit('test.pong', { from: 'TestService' })
    })
  }
  
  registerRoutes(app) {
    // 注册测试路由
    app.get('/api/test', c => {
      return c.json({
        service: 'TestService',
        config: {
          namespace: this.config.get('base.namespace'),
          port: this.config.get('base.port')
        },
        logger: {
          level: this.logger.getLevel()
        },
        database: {
          connected: this.db !== null
        }
      })
    })
    
    app.get('/api/test/emit', async c => {
      await this.eventBus.emit('test.ping', { time: Date.now() })
      return c.json({ message: 'Event emitted' })
    })
    
    return true
  }
  
  registerScheduledTasks(scheduler) {
    // 注册测试任务
    scheduler.registerTask('test.heartbeat', {
      cron: '*/30 * * * * *',  // 每30秒
      runOnInit: false
    }, async () => {
      this.logger.debug('TestService', 'Heartbeat task executed')
    })
  }
}